This unit continues our exploration of Principal Component Analysis (PCA).
We deep-dive into explained variance ratios, work through a complete hand-computed PCA example on the Iris dataset,
then run a comparative case study pitting filter methods, wrapper methods, and PCA against each other on the
Adult Census Income dataset. Finally, we introduce the mathematical foundation of the Naive Bayes
classifier starting from Bayes' Theorem.
Learning Objectives
Compute and interpret Explained Variance Ratios from eigenvalues and select \(k\) components via a scree plot
Execute a step-by-step hand calculation of PCA on a small dataset (Iris)
Compare Filter, Wrapper, and PCA feature engineering experimentally via AUC on Adult Census data
State and explain Bayes' Theorem and the conditional independence "naive" assumption
Derive the Naive Bayes classification rule from first principles
2. Theory
2.1 PCA Recap — Step-by-Step Process
PCA has two distinct phases. The parameters (mean, std, projection matrix \(W\)) are learned on the training set only.
Learning Phase
Application Phase
Standardize the \(d\)-dimensional training dataset (\(X_{\text{train}}\))
Construct the covariance matrix \(\Sigma\) of shape \(d \times d\)
Decompose \(\Sigma \rightarrow\) eigenvectors + eigenvalues via eigendecomposition
Sort eigenvalues in decreasing order to rank eigenvectors
Select top \(k\) eigenvectors corresponding to the \(k\) largest eigenvalues (\(k \lt d\))
Build projection matrix \(W\) of shape \(d \times k\) from top-\(k\) eigenvectors
Transform both \(X_{\text{train}}\) and \(X_{\text{test}}\) using \(W\) to get \(k\)-dimensional features
2.2 Explained Variance Ratio & Scree Plot
Each eigenvalue \(\lambda_j\) quantifies the variance captured by its corresponding principal component.
The proportion of total variance explained by component \(j\) is:
Let us compute PCA on the first 8 Iris samples. Because all 4 features are measured in cm with similar ranges, we only center (we do not divide by std for pedagogical clarity).
PCA preserves total variance — it just re-rotates the axes! ✓
📌 Standardization Rule-of-Thumb
We skipped full standardization here (cm features with similar scales). Always use full standardization when:
Features have different units (age in years vs. income in USD)
Features have vastly different numerical ranges (0–1 percentages vs. 10,000–1,000,000 salaries)
You want equal a-priori importance for every feature
2.4 Case Study — Feature Engineering Showdown (Adult Census Income)
We compare four feature-engineering pipelines on the Adult Income dataset
(predict income > $50K / year, ~30K rows, 14 mixed features). Evaluation metric: AUC.
Pipeline
# Features Used
Training AUC
Test AUC
Training Time
Baseline (all features)
14
0.921
0.884
1.0× (ref)
Filter (χ² + ANOVA)
9
0.910
0.881
0.8×
Wrapper (Fwd/Bwd + KNN)
7
0.932
0.876
12.4×
PCA (k = 6 components)
6
0.914
0.888
1.3×
🔍 Case Study Observations (click to expand)
Wrapper had the highest train AUC but lowest test AUC — classic overfitting to the validation folds.
PCA achieved the highest test AUC using only 6 orthogonal components — decorrelation helps generalization.
Filter was fastest, nearly matched baseline, and is a strong first choice for quick iteration.
Wrapper was ~12× slower (re-trains model for every candidate feature set) — expensive at scale.
2.5 Bayes' Theorem — Foundation of Naive Bayes
Reverend Thomas Bayes' 1763 theorem lets us update beliefs given evidence. For a class label \(y\)
and feature vector \(x = (x_1, x_2, \dots, x_d)\):
\(P(y)\) — Prior probability of class \(y\) (frequency in training data)
\(P(x \mid y)\) — Likelihood of features \(x\) conditional on class \(y\)
\(P(x)\) — Evidence (same for all classes, so we can ignore it during prediction)
\(P(y \mid x)\) — Posterior probability — what we want
2.6 The "Naive" Conditional Independence Assumption
The hard part is \(P(x \mid y) = P(x_1, x_2, \dots, x_d \mid y)\) — a full joint distribution over \(d\) features is
exponentially hard. Naive Bayes makes a strong but computationally convenient assumption:
Naive Assumption: All features are conditionally independent given the class label.
\[
P(x \mid y) = \prod_{i=1}^{d} P(x_i \mid y)
\]
This is rarely literally true (features often correlate!), but Naive Bayes works surprisingly well in practice
(text classification, spam detection, sentiment analysis) because only the rank order of posteriors matters for classification,
not their absolute calibration.
2.7 Naive Bayes Classification Rule
For a new sample \(x\), pick the class \(\hat{y}\) that maximizes the unnormalized log-posterior
(log avoids numerical underflow and turns products into sums):
(c) A rule-of-thumb says "keep components until ≥ 95 % variance". Roughly how many components would that be for Wine?
First 9 eigenvalues sum to ≈ 12.4, giving ≈ 95.4 %. So k ≈ 9 components.
Example 2: Bayes' Theorem — Medical Diagnostic
A rare disease affects 1 % of the population (\(P(D) = 0.01\)). A test is 99 % sensitive
(\(P(+ \mid D) = 0.99\)) and 95 % specific (\(P(- \mid \neg D) = 0.95\)).
You test positive. What is \(P(D \mid +)\)? Click to reveal.
Even a 99%/95% accurate test has only ~17% PPV on a 1% prevalence disease (base-rate fallacy!) — always use Bayes.
Example 3: Pipeline Winner Interpretation
Back to the Adult Census case study. Five students interpret the results. Who is correct?
Student
Claim
Ali
Wrapper is best because its training AUC is highest (0.932).
Bilal
PCA is best because its test AUC is highest (0.888).
Chloe
Filter is best because it's fastest.
Dua
Wrapper is overfitting because test AUC (0.876) < train AUC (0.932).
Bilal and Dua are both correct.
Bilal: Test-set performance on unseen data is the gold standard for generalization.
Dua: The large train–test gap for Wrapper is textbook overfitting to validation-fold feedback.
Ali is wrong (train AUC is optimistic), and Chloe confuses speed with quality.
Moral: The same email flips classification because the prior changed.
When spam is rare (1%), the evidence of two spammy words isn't strong enough to overcome the low base rate.
This is why priors matter!
5. Try It Yourself
Problem 1 — EVR & k Selection
Sorted eigenvalues from a 5-feature PCA run: \([2.5,\; 1.5,\; 0.7,\; 0.2,\; 0.1]\).
Compute the total variance preserved by PCA (hint: sum of eigenvalues).
Compute the individual and cumulative EVR for each component.
How many PCs should you keep for a ≥ 90 % cumulative-variance threshold?
Factory machines M1, M2, M3 produce 20 %, 30 %, 50 % of total output respectively.
Their defect rates are 5 %, 3 %, 1 %. An item is randomly sampled and found defective.
Which machine is it most likely to have come from? Compute all 3 posteriors.
Answer all 5 MCQs. Click on an option to get instant feedback.
Your score: 0 / 5
7. Key Takeaways
Explained Variance Ratio: \(\text{EVR}_j = \lambda_j / \sum_i \lambda_i\). The scree plot visualizes EVR and the elbow guides \(k\)-selection (common thresholds: 90%, 95%, or the "elbow").
Variance is conserved under PCA rotation: Sum of eigenvalues = Sum of original feature variances. PCA doesn't "lose" information globally — it reorganizes variance into orthogonal axes.
Standardize before PCA whenever feature scales differ. Without standardization, income (in dollars) will dominate PCA over temperature (in °C).
In the case study, PCA generalized best (highest test AUC), Wrapper overfit (highest train AUC, slowest), Filter was fastest with near-baseline quality. No single method is always best — run the experiment.
Bayes' Theorem: \(P(y \mid x) = P(x \mid y)P(y)/P(x)\). The prior \(P(y)\) is critical. A "99 % accurate" test on a rare disease still gives a low posterior.
Naive Bayes assumes conditional feature independence: \(P(x \mid y) = \prod P(x_i \mid y)\). Take logs to turn products into sums and avoid underflow. Works extremely well on text despite the "naive" assumption.
8. Common Pitfalls
Forgetting to standardize before PCA. The resulting PCs will be meaningless if features are on incomparable scales. Always use StandardScaler for heterogeneous data.
Fitting PCA on the full dataset before train/test splitting. This leaks test-set distribution information. Fit on train only, then apply the learned \(W\) to both train and test.
Interpreting individual PCA components as meaningful "features." PCs are linear combinations of all original features and are often not human-interpretable. Use factor analysis if interpretability is critical.
Multiplying probabilities directly in Naive Bayes (not log space). For even moderate \(d\), \(\prod P(x_i \mid y)\) underflows to zero on floating-point hardware. Always use log-space arithmetic.
Zero-frequency problem (P(word∣class)=0). A single unseen feature zeros the entire posterior. Always use Laplace (add-α) smoothing on categorical Naive Bayes likelihoods.
Confusing "Wrapper overfits on training" with "Wrapper is useless." Wrappers are valid — you just need to couple them with strong regularization, a holdout validation set, and/or use them only on small feature subsets.